<template>

  <div class="DataBoard_container main_container">

    <div class="main_header">
      <div class="padding_container">
        <div class="left">
          <Breadcrumb />
        </div>
        <div class="right">

          <span v-if="temperatureData&&temperatureData.temp" class="main_header_left_text">温度：{{ temperatureData.temp }}</span>
          <span v-if="temperatureData&&temperatureData.humi" class="main_header_left_text">湿度：{{ temperatureData.humi }}</span>
          <a class="right_setting" @click="setup">
            <svg-icon icon-class="设置" />
          </a>
        </div>
      </div>
    </div>
    <div class="DataBoard_container_main">
      <div class="DataBoard_container_main_statistics">
        <div v-for="item in 6" :key="item" class="statistics_item">
          <a v-if="showStatisticsItem&&showStatisticsItem.length>=item" @click="routeGo(showStatisticsItem[item-1])">
            <div class="statistics_item_icon" :style="{backgroundColor:showStatisticsItem[item-1].bgColor}"><svg-icon :icon-class="showStatisticsItem[item-1].icon" /></div>
            <div class="statistics_item_number">{{ statisticsData[showStatisticsItem[item-1].dataKey] }}</div>
            <div class="statistics_item_background1" />
            <div class="statistics_item_background" />
            <div class="statistics_item_name">{{ showStatisticsItem[item-1].name }}</div>
          </a>
          <div v-else />
        </div>
      </div>
      <div class="DataBoard_container_main_charts">
        <div v-for="(item,index) in showChartItem" :key="index" class="charts_item" :class="item.length?'double':''">
          <LocationDistribution v-if="item.component=='LocationDistribution'" />
          <MaintainPlanTimelinessRate v-if="item.component=='MaintainPlanTimelinessRate'" />
          <RepairTypeDistribution v-if="item.component=='RepairTypeDistribution'" />
          <DegreeDistribution v-if="item.component=='DegreeDistribution'" />
          <CheckPlanCompletedRatio v-if="item.component=='CheckPlanCompletedRatio'" />
          <MaintenanceCostStatistics v-if="item.component=='MaintenanceCostStatistics'" />
          <MachineHaltDuration v-if="item.component=='MachineHaltDuration'" />
          <SparePartsConsumptionRanking v-if="item.component=='SparePartsConsumptionRanking'" />

          <TaskStatistics v-if="item.component=='TaskStatistics'" />

          <EquipmentStatusTodays v-if="item.component == 'EquipmentStatusTodays'" />
          <AlarmInformation v-if="item.component == 'AlarmInformation'" />
          <DetailInspectedToday v-if="item.component == 'DetailInspectedToday'" />
          <OEESequenceDiagram v-if="item.component == 'OEESequenceDiagram'" :target-number="OEENumber" />
          <OnDutyPersonnel v-if="item.component=='OnDutyPersonnel'" />
          <CapacityStatistics v-if="item.component == 'CapacityStatistics'" :target-number="capacityNumber" />
          <RankingFaultTimes v-if="item.component == 'RankingFaultTimes'" />
          <WorkshopEquipmentRealTime v-if="item.component == 'WorkshopEquipmentRealTime'" />
          <EquipmentUtilization v-if="item.component == 'EquipmentUtilization'" />
          <DetailsMaintainMonth v-if="item.component=='DetailsMaintainMonth'" />
          <OverdueWorkOrder v-if="item.component=='OverdueWorkOrder'" />
          <WorkOrderDetailsInRepair v-if="item.component=='WorkOrderDetailsInRepair'" />

          <EquipmentPower v-if="item.component == 'EquipmentPower'" :device-ids="item.deviceIds" />
          <PowerDistribution v-if="item.component=='PowerDistribution'" />
          <ElectricityYearOnYear v-if="item.component=='ElectricityYearOnYear'" />
          <DailyElectricity v-if="item.component=='DailyElectricity'" :threshold="item.threshold" />
          <EquipmentStatusStatistic v-if="item.component == 'EquipmentStatusStatistic'" :device-ids="item.deviceIds" />
          <MaintenanceHoursThisMonth v-if="item.component=='MaintenanceHoursThisMonth'" />
        </div>
      </div>

    </div>
  </div>
</template>

<script>

import { deviceHeadDate, getTemperature } from '@/api/equipmentManage/equipmentReport/dataBoard' // 接口
import TaskStatistics from '../../../equipmentManage/equipmentReport/dataBoard/components/TaskStatistics.vue' // 任务统计
import LocationDistribution from './components/LocationDistribution' // 设备位置分布
import MaintainPlanTimelinessRate from './components/MaintainPlanTimelinessRate' // 保养计划及时率
import MachineHaltDuration from './components/MachineHaltDuration' // 停机时间排行
import RepairTypeDistribution from './components/RepairTypeDistribution' // 故障类型分布
import DegreeDistribution from './components/EmergencyDegreeDistribution' // 设备紧急程度分布
import CheckPlanCompletedRatio from '../../../system/largeScreen/components/checkPlanFinishedRate.vue' // 点检计划完成率
import MaintenanceCostStatistics from './components/MaintenanceCostStatistics'
import SparePartsConsumptionRanking from './components/SparePartsConsumptionRanking'
import EquipmentStatusTodays from '../../../system/largeScreen/components/EquipmentStatusTodays.vue'
import AlarmInformation from '../../../system/largeScreen/components/AlarmInformation.vue'
import OEESequenceDiagram from '../../../system/largeScreen/components/OEESequenceDiagram.vue'
import OnDutyPersonnel from '../../../system/largeScreen/components/OnDutyPersonnel.vue'
import CapacityStatistics from '../../../system/largeScreen/components/CapacityStatistics.vue'
import RankingFaultTimes from '../../../system/largeScreen/components/RankingFaultTimes.vue'
import WorkshopEquipmentRealTime from '../../../system/largeScreen/components/WorkshopEquipmentRealTime.vue'
import EquipmentUtilization from '../../../system/largeScreen/components/EquipmentUtilization.vue'
import DetailInspectedToday from '../../../system/largeScreen/components/DetailInspectedToday.vue'
import DetailsMaintainMonth from '../../../system/largeScreen/components/DetailsMaintainMonth.vue'
import OverdueWorkOrder from '../../../system/largeScreen/components/OverdueWorkOrder.vue'
import WorkOrderDetailsInRepair from '../../../system/largeScreen/components/WorkOrderDetailsInRepair.vue'

import EquipmentPower from '@/views/system/largeScreen/components/EquipmentPower.vue' // 设备功率
import PowerDistribution from '@/views/system/largeScreen/components/PowerDistribution.vue' // 峰平谷电量
import ElectricityYearOnYear from '@/views/system/largeScreen/components/ElectricityYearOnYear.vue' // 电量同比分析
import DailyElectricity from '@/views/system/largeScreen/components/DailyElectricity.vue' // 日用电量趋势
import EquipmentStatusStatistic from '@/views/system/largeScreen/components/EquipmentStatusStatistic.vue' // 今日设备状态
import MaintenanceHoursThisMonth from '@/views/system/largeScreen/components/MaintenanceHoursThisMonth.vue'
import Setup from './components/newSetUp.vue'
import { getPageSettings } from '@/api/common/common'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
  name: 'DataBoard',
  components: {
    TaskStatistics, LocationDistribution, MaintainPlanTimelinessRate,
    MachineHaltDuration, RepairTypeDistribution, DegreeDistribution, CheckPlanCompletedRatio,
    MaintenanceCostStatistics, SparePartsConsumptionRanking,
    EquipmentStatusTodays,
    AlarmInformation,
    OEESequenceDiagram,
    OnDutyPersonnel,
    CapacityStatistics,
    RankingFaultTimes,
    WorkshopEquipmentRealTime,
    EquipmentUtilization,
    DetailInspectedToday,
    DetailsMaintainMonth,
    OverdueWorkOrder,
    WorkOrderDetailsInRepair,
    EquipmentPower,
    PowerDistribution,
    ElectricityYearOnYear,
    DailyElectricity,
    EquipmentStatusStatistic,
    MaintenanceHoursThisMonth
  }, // 组件注册
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  data() {
    return {
      capacityNumber: 100,
      OEENumber: 100,
      timer: undefined,
      id: '',
      statisticsItem: [ // 可选的统计数据项
        { name: '设备总数', icon: '设备总数', dataKey: 'deviceTotalNumber', bgColor: '#FFC9C94D', isShow: true },
        { name: '今日点检（含待点检）', icon: '今日待点检', dataKey: 'waitCheckNumber', bgColor: '#FFC9FB4D', isShow: true },
        { name: '本月待保养', icon: '本月待保养', dataKey: 'waitMaintainNumber', bgColor: '#D3C9FF4D', isShow: true },
        { name: '维修中设备数', icon: '维修中设备数', dataKey: 'repairNumber', bgColor: '#FFEBC94D', isShow: true },
        { name: '安全库存报警', icon: '安全库存报警', dataKey: 'safetyStockAlarm', bgColor: '#C9FFE14D', isShow: true },
        { name: '本月维修工时(h)', icon: '本月维修工时', dataKey: 'monthRepairTime', bgColor: '#B1FCFF4D', isShow: false },
        { name: '今日点检逾期数', icon: '今日点检超期数', dataKey: 'overdueCheckNumber', bgColor: '#C9EEFF4D', isShow: true },
        { name: '备件待盘点工单', icon: '待盘点工单', dataKey: 'waitSpareCheckNumber', bgColor: '#F7FFC94D', isShow: false },
        { name: '维修工单', icon: '维修中工单', dataKey: 'repairRecordNumber', bgColor: '#B1FCFF4D', isShow: false }

      ],
      chartItem: [// 可选的图表项
        { name: '设备紧急程度分布', component: 'DegreeDistribution', isShow: true },
        { name: '点检计划完成率', component: 'CheckPlanCompletedRatio', isShow: true },
        { name: '维修费用统计', component: 'MaintenanceCostStatistics', isShow: true },
        { name: '备件消耗排行', component: 'SparePartsConsumptionRanking', isShow: true },
        { name: '设备位置分布', component: 'LocationDistribution', isShow: true },
        { name: '保养计划及时率', component: 'MaintainPlanTimelinessRate', isShow: true },
        // { name: '停机时间排行', component: 'MachineHaltDuration' },
        { name: '故障类型分布', component: 'RepairTypeDistribution', isShow: true },
        { name: '报警信息', component: 'AlarmInformation', isShow: true },
        { name: '产能统计', component: 'CapacityStatistics', number: 100, isShow: true },
        { name: '今日点检明细', component: 'DetailInspectedToday', isShow: true },
        { name: '本月待保养明细', component: 'DetailsMaintainMonth', isShow: true },
        { name: '设备状态统计', component: 'EquipmentStatusTodays', isShow: true },
        { name: '设备利用率', component: 'EquipmentUtilization', isShow: true },
        { name: 'OEE时序图', component: 'OEESequenceDiagram', number: 100, isShow: true },
        { name: '已逾期工单', component: 'OverdueWorkOrder', isShow: true },
        { name: '维修工单明细', component: 'WorkOrderDetailsInRepair', isShow: true },
        { name: '任务统计', component: 'TaskStatistics', length: '2', isShow: true },
        { name: '设备故障占比', component: 'MaintenanceHoursThisMonth', isShow: false },
        { name: '设备功率', component: 'EquipmentPower', deviceIds: '', isShow: false },
        { name: '峰平谷电量', component: 'PowerDistribution', isShow: false },
        { name: '电量同比分析', component: 'ElectricityYearOnYear', isShow: false },
        { name: '今日设备状态', component: 'EquipmentStatusStatistic', deviceIds: [], isShow: false },
        { name: '日用电量趋势', component: 'DailyElectricity', threshold: 0, isShow: false }
      ],
      statisticsData: {},
      temperatureData: {},
      pageId: '设备数据看板',
      showStatisticsItem: [], // 真正展示的统计数据项
      showChartItem: [] // 真正展示的图表项
    }
  },
  mounted() {
    this.getPageSettings()
    this.getStatisticsData()
    this.timer = setInterval(() => {
      this.getStatisticsData()
    }, this.$store.state.common.refreshFrequency * 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    // 获取顶部统计数据
    getStatisticsData() {
      deviceHeadDate().then(res => {
        this.statisticsData = res.data
      })

      getTemperature().then(res => {
        this.temperatureData = res.data
      })
    },
    // 设置
    setup() {
      // 遍历 chartItem ，如果有新加的 chartItem，但是之前保存的showChartItem 里没有 ，那么它也要传到设置页，不然设置页看不到
      const cacheChartItem = this.$deepClone(this.showChartItem)
      // this.chartItem.forEach(item => {
      //   if (!this.showChartItem.some(item2 => item2.component == item.component)) {
      //     cacheChartItem.push(item)
      //   }
      // })
      // statisticsItem 也一样
      const cacheStatisticsItem = this.$deepClone(this.showStatisticsItem)
      // this.statisticsItem.forEach(item => {
      //   if (!this.showStatisticsItem.some(item2 => item2.dataKey == item.dataKey)) {
      //     cacheStatisticsItem.push(item)
      //   }
      // })
      this.$layer.iframe({
        // 弹框
        content: {
          content: Setup, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            settingData: {
              StatisticsItem: cacheStatisticsItem, // 显示设置的数据
              ChartItem: cacheChartItem, // 字段搜索的数据
              id: this.id,
              pageId: this.pageId // 页面唯一标识
            }
          } // props
        },
        area: ['1000px', '700px'],
        title: '看板设置', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    getPageSettings() {
      getPageSettings({ userId: this.userId, pageId: this.pageId }).then(res => {
        if (res.data.json) {
          const pageSetings = res.data.json
          pageSetings.ChartItem.forEach(ele => {
            ele.isShow = true
          })
          this.showStatisticsItem = pageSetings.StatisticsItem
          this.showChartItem = pageSetings.ChartItem

          this.id = res.data.id
        } else {
          this.showStatisticsItem = this.$deepClone(this.statisticsItem.filter(item => item.isShow))
          this.showChartItem = this.$deepClone(this.chartItem.filter(item => item.isShow))
        }
        this.OEENumber = this.showChartItem.filter(item => item.component == 'OEESequenceDiagram')[0].number
        this.capacityNumber = this.showChartItem.filter(item => item.component == 'CapacityStatistics')[0].number
      })
    },
    routeGo(data) {
      console.log(data)
      let routeData = {} // 跳转过去之后带上的查询参数
      let router = {} // 跳转的路由
      switch (data.dataKey) {
        case 'deviceTotalNumber': // 设备总数
          routeData = {
            status: 1
          }
          router = '/equipmentManage/baseInfo/equipmentInfo'
          break
        case 'waitCheckNumber': // 今日待点检
          routeData = {
            status: [0, 1],
            planTime: [moment(new Date()).format('YYYY-MM-DD') + ' 00:00',
              moment(new Date()).format('YYYY-MM-DD') + ' 23:59']
          }
          router = '/equipmentManage/equipmentCheck/checkRecord'
          break
        case 'waitMaintainNumber': // 本月待保养
          routeData = {
            status: 0,
            planTime: [moment(new Date()).add('month', 0).format('YYYY-MM') + '-01' + ' 00:00',
              moment(moment(new Date()).add('month', 0).format('YYYY-MM') + '-01').add('month', 1).add('days', -1).format('YYYY-MM-DD') + ' 23:59']
          }
          router = '/equipmentManage/equipmentMaintain/maintainRecord'
          break
        case 'repairNumber': // 维修中设备数
          routeData = {
            statusPc: [4, 0]
          }
          router = '/equipmentManage/equipmentRepair/repairRecord'
          break
        case 'safetyStockAlarm': // 安全库存报警
          routeData = {
            safeStock: '1'
          }
          router = '/equipmentManage/sparePartsManagement/sparePartsStock'
          break
        case 'overdueCheckNumber': // 今日点检超期数
          routeData = {
            status: [3],
            planTime: [moment(new Date()).format('YYYY-MM-DD') + ' 00:00',
              moment(new Date()).format('YYYY-MM-DD') + ' 23:59']
          }
          router = '/equipmentManage/equipmentCheck/checkRecord'
          break
        case 'waitSpareCheckNumber': // 待盘点工单
          routeData = {
            status: '0'
          }
          router = '/equipmentManage/sparePartsManagement/sparePartsTakeStock'
          break
        case 'repairRecordNumber': // 维修中工单
          routeData = {
            statusPc: [4, 0]
          }
          router = '/equipmentManage/equipmentRepair/repairRecord'
          break
        case 'monthRepairTime': // 维修中工单
          routeData = {
            searchTime: [this.$moment().startOf('month').format('YYYY-MM-DD') + ' 00:00',
              this.$moment(new Date()).format('YYYY-MM-DD') + ' 23:59']
          }
          router = '/equipmentManage/equipmentReport/serviceReport'
          break
      }
      // 查询参数存入 vuex
      this.$store.state.common.routeData = routeData

      // 进行页面跳转
      this.$router.push({ path: router })
    }
  }
}
</script>

<style lang="less" scoped>
  .checkPlan_month{
    padding-top: 16px;
    padding-right: 20px;
  }
.DataBoard_container{
  //box-shadow: inset 0px 0px 12px 0px rgba(29, 65, 134, 0.18);
 background-color: #f7f8fa;
  //background-color: #5a5e66;
  overflow-y: auto;
  .right_setting{
    font-size: 20px;
  }
  .DataBoard_container_main{
    padding: 10px 20px 20px 20px;
  }

  .DataBoard_container_main_statistics{
    width: 100%;
    display: flex;

    .statistics_item{
      width: 16.6666%;
      height: 100px;
      border-radius: 4px;
      margin-left: 20px;

      .statistics_item_background1{
        width: 100%;
        height: 30px;
      }
      .statistics_item_background{
        width: 100%;
        height: 70px;
        background-color: white;
        border-radius: 4px;
      }
      .statistics_item_icon{
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background-color: rgba(255, 201, 201, 1);
        float: left;
        left: 20px;
        position: relative;
        font-size: 26px;
        display: flex;justify-content: center;align-items: center;
      }
      .statistics_item_number{
        float: right;
        right: 20px;
        position: relative;
        color: rgba(51, 51, 51, 1);
        font-size: 36px;
        height: 60px;
        line-height: 60px;
      }
      .statistics_item_name{
        float: right;
        right: 20px;
        position: relative;
        color: rgba(153, 153, 153, 1);
        font-size: 16px;
        top: -35px;
      }
    }

    .statistics_item:hover{
      .statistics_item_background{
        background-color: rgba(56, 123, 252, 0.5);
      }
      .statistics_item_name{
        color: white;
      }
    }

    .statistics_item:first-child{
      margin-left: 0px;
    }
  }

  .DataBoard_container_main_charts{
    width: 100%;
    display: flex;flex-wrap: wrap;justify-content: space-between;

    .charts_item{
      width: calc(50% - 10px);
      background-color: white;
      height: 310px;
      margin-top: 20px;
      border-radius: 4px;
    }
    .charts_item.double{
      width: 100%;
    }

  }

}
.main_header_left_text{
  //color: #333333;
  margin-right: 20px;
  color: #00bf00;
  line-height: 28px;
  font-size: 16px;
}
</style>
